package com.itheima.auth.controller.v1;

import com.itheima.auth.service.AuthService;
import com.itheima.model.admin.dtos.LoginDto;
import com.itheima.model.common.dtos.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 认证控制器
 * 
 * @author itheima
 */
@RestController
@RequestMapping("/api/v1/auth")
@Api(tags = "认证管理接口")
@Slf4j
public class AuthController {

    @Autowired
    private AuthService authService;

    /**
     * 管理员登录
     */
    @PostMapping("/login")
    @ApiOperation("管理员登录")
    public ResponseResult login(@RequestBody LoginDto dto) {
        return authService.login(dto);
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    @ApiOperation("退出登录")
    public ResponseResult logout(@RequestHeader("Authorization") String authHeader) {
        // 从Header中提取token（格式：Bearer xxxxx）
        String token = extractToken(authHeader);
        return authService.logout(token);
    }

    /**
     * 刷新Token
     */
    @PostMapping("/refresh")
    @ApiOperation("刷新Token")
    public ResponseResult refreshToken(@RequestHeader("Authorization") String authHeader) {
        String token = extractToken(authHeader);
        return authService.refreshToken(token);
    }

    /**
     * 获取当前登录管理员信息
     */
    @GetMapping("/current")
    @ApiOperation("获取当前登录管理员信息")
    public ResponseResult getCurrentAdmin(@RequestHeader("Authorization") String authHeader) {
        String token = extractToken(authHeader);
        return authService.getCurrentAdmin(token);
    }

    /**
     * 从Authorization Header中提取Token
     * 
     * @param authHeader Authorization头的值，格式：Bearer xxxxx
     * @return JWT Token
     */
    private String extractToken(String authHeader) {
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            return authHeader.substring(7);
        }
        return authHeader;
    }
}

